package my2Cents;

import java.awt.Component;
import java.awt.Dimension;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JPanel;

public class JComponentList extends JPanel {
	private static final long serialVersionUID = 1L;
	private Vector<Component> components;
	
	public JComponentList() {
		components = new Vector();
	}
	
	public Component add(Component c) {
		super.add(c);
		components.add(c);
		resizeToFit();
		firePropertyChange("ListModified",1,0);
		return c;
	}
	
	public void clear() {
		for(int i=0; i<length(); i++) {
			super.remove(components.get(i));
		}
		components.clear();
		resizeToFit();
		firePropertyChange("ListModified",1,0);
	}
	
	public int length() {
		return components.size();
	}
	
	public void remove(Component c) {
		super.remove(c);
		components.remove(c);
		resizeToFit();
		firePropertyChange("ListModified",1,0);
	}
	
	public void resizeToFit() {
		int lastHeight = 0;
		for(int i=0; i<components.size(); i++) {
			Component c = (Component) components.get(i);
			c.setSize(this.getWidth(),c.getHeight());
			c.setPreferredSize(new Dimension(this.getWidth(),c.getHeight()));
			c.setLocation(0,lastHeight);
			lastHeight += c.getHeight();
		}
		this.validate();
		this.setPreferredSize(new Dimension(this.getWidth(),lastHeight));
		this.repaint();
		this.invalidate();
	}
}